#include "formslavestate.h"
#include "ui_formslavestate.h"
#include "dcsproto/proto.h"

#include <QDebug>
#include <QTimer>
#include <QThread>
#include <QColor>
#include <global.h>

FormSlaveState::FormSlaveState(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::FormSlaveState)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags() | Qt::Dialog);
    setWindowModality(Qt::ApplicationModal);
    setAttribute(Qt::WA_DeleteOnClose);

    mDbopt = new DCSDbOperator();
    quint8 iface;
    if (!DCSDbOperator::getMasterParameterInterface(iface))
    {
        qDebug() << "db get interface error,set to default";
        iface = UDP_IFACE_EN_WAN;
    }

    if (iface == UDP_IFACE_EN_WAN)
    {
        mUdp = new UdpWorker(INTERFACE_WAN_NAME);
    }
    else
    {
        mUdp = new UdpWorker(INTERFACE_LAN_NAME);
    }

    cmdSendTimer.setSingleShot(false);
    cmdSendTimer.setInterval(100);
    cmdSendTimer.start();

    mDbopt->getMasterParameterSlaveNum(mslaveNum);

    ui->tableWidget->setRowCount(32);
    ui->tableWidget->setColumnCount(8);

    //初始化各分控显示状态
    for (int i = 0; i < 32; i++)
    {
        bool finish = false;

        for (int j = 0; j < 8; j++)
        {
            unsigned int count = i * 8 + j + 1;

            if (count <= mslaveNum)
            {
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
                ui->tableWidget->item(i, j)->setTextAlignment(Qt::AlignCenter);
                ui->tableWidget->item(i, j)->setBackground(QColor(0x96, 0x0D, 0x19));
                ui->tableWidget->item(i, j)->setText(QString::number(count));

                //初始化状态为离线
                mOnline.append(SlaveOnlineState(count, 0));
                continue;
            }

            finish = true;
            break;
        }

        if (finish)
        {
            break;
        }
    }

    qDebug() << "init item count:" << mOnline.count();
    connect(&cmdSendTimer, &QTimer::timeout, this, &FormSlaveState::on_cmdSendTimerout);
    connect(mUdp, &UdpWorker::dataRecvdBytes, this, &FormSlaveState::on_dataRecved);

    qDebug() << "[FormSlaveState] \t Constructor";
}

FormSlaveState::~FormSlaveState()
{
    delete ui;

    cmdSendTimer.stop();

    delete mDbopt;
    delete mUdp;
    qDebug() << "[FormSlaveState] \t Destructor";
}

void FormSlaveState::on_pushButtonSlaveStatReturn_clicked()
{
    close();
}

/**
 * @brief FormSlaveState::on_Timerout
 *
 */
void FormSlaveState::on_cmdSendTimerout()
{
    char buf[60];

    //先发ID自动分配命令
    struct slave_id_set_pdu pdu;
    memset(buf, 0x0, sizeof(buf));
    memset(&pdu, 0x0, sizeof(pdu));
    pdu.type = EN_SLAVE_ID_SET_TYPE_AUTO;
    pdu.param.fist_para.id = 0x001;
    aklt_proto_encode((unsigned char *) buf, TYP_SLAVE_BROADCAST_FREQ_SET, CMD_SLAVE_ID_CONF_FREQ_SET, 0x0000,
                      (unsigned char *) &pdu, sizeof(pdu), SLAVE_BROADCAST);
    mUdp->dataSend(buf, 60);

    //然后发广播查询ID自动分配命令
    struct slave_conf_read_pdu autoidPdu;
    memset(buf, 0x0, 60);
    memset(&autoidPdu, 0x0, sizeof(autoidPdu));
    autoidPdu.conf_id = SLAVE_CONF_ID_AUTO;
    aklt_proto_encode((unsigned char *) buf, TYP_SLAVE_CONF_READ, CMD_SLAVE_CONF_READ, 10000,
                      (unsigned char *) &autoidPdu, sizeof(autoidPdu), SLAVE_BROADCAST);
    mUdp->dataSend(buf, 60);
    cmdSendTimer.setInterval(5000);

    //更新在线状态显示
    QVector<SlaveOnlineState>::iterator iter;
    for (iter = mOnline.begin(); iter != mOnline.end(); iter++)
    {
        unsigned int x, y;

        x = (iter->id() - 1) / 8;
        y = (iter->id() - 1) % 8;

        if (iter->state() == 1)
        {
            ui->tableWidget->item(x, y)->setBackground(QColor(0x63, 0xBF, 0x40));
        }
        else
        {
            ui->tableWidget->item(x, y)->setBackground(QColor(0x96, 0x0D, 0x19));
        }
        iter->setState(0);
    }
}

void FormSlaveState::on_dataRecved(QByteArray &data)
{
    struct akltproto aklt;
    aklt_proto_decode(&aklt, (unsigned char *) (data.data()), data.size());
    delete aklt.data;

    //设置在线状态
    if (aklt.id <= mslaveNum)
    {
        mOnline.append(SlaveOnlineState(aklt.id, 1));
    }
}
